import Entity.Appid;
import Entity.Message;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import tools.check;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

@WebServlet("/login/dgut")
public class loginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("进入该servlet");
        HttpSession session = request.getSession(true);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        StringBuffer param = new StringBuffer();
        String token = (String) session.getAttribute("token");
        System.out.println(token);
        String userip = request.getRemoteAddr();
        param.append("token=" + token + "&");
        param.append("appid=" + "javaee" + "&");
        param.append("appsecret=" + "b3b52e43ccfd" + "&");
        param.append("userip=" + userip);
        HttpPost httpPost = new HttpPost("https://cas.dgut.edu.cn/ssoapi/v2/checkToken" + "?" + param);
        // 设置ContentType(注:如果只是传普通参数的话,ContentType不一定非要用application/json)
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf8");

        // 响应模型
        CloseableHttpResponse res = null;
        res = httpClient.execute(httpPost);
        HttpEntity entity2 = res.getEntity();
        while (entity2 == null) {
            httpPost = new HttpPost("https://cas.dgut.edu.cn/ssoapi/v2/checkToken" + "?" + param);
            res = httpClient.execute(httpPost);
            entity2 = res.getEntity();
        }
        String str = EntityUtils.toString(entity2, "utf-8");
        //System.out.println(str);
        Jsonb jsonb = JsonbBuilder.create();
        // 利用jsonb把json字符串转换为对象
        Appid testDTO = jsonb.fromJson(str, Appid.class);
        System.out.println(testDTO.getmessage());
        if (testDTO != null && testDTO.getmessage().equals("success")) {

            session.setAttribute("message", testDTO.getmessage());
            StringBuffer param2 = new StringBuffer();
            String openid = testDTO.getopenid();
            String access_token = testDTO.getaccess_token();
            param2.append("openid=" + openid + "&");
            param2.append("access_token=" + access_token);
            System.out.println(param2);
            HttpPost httpPost2 = new HttpPost("https://cas.dgut.edu.cn/oauth/getUserInfo" + "?" + param2);
            // 设置ContentType(注:如果只是传普通参数的话,ContentType不一定非要用application/json)
            //httpPost2.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf8");
            //System.out.println("1");

            // 响应模型
            res = httpClient.execute(httpPost2);
            HttpEntity entity = res.getEntity();
            while (entity == null) {
                httpPost2 = new HttpPost("https://cas.dgut.edu.cn/oauth/getUserInfo" + "?" + param2);
                res = httpClient.execute(httpPost2);
                entity = res.getEntity();
            }
            String str2 = EntityUtils.toString(entity, "utf-8");
            System.out.println(str2);
            // 利用jsonb把json字符串转换为对象
            Message MessageDTO = jsonb.fromJson(str2, Message.class);
            //{"username":"201741404127","name":"黄鑫杰","faculty":200,"wx_openid":"o7n4SxOSQr-f1TnqgOSADP4KFksQ",
            // "group":"Student","faculty_title":"计算机与网络安全学院","openid":"20b72e27fc8c2f07dd0509d04b08c7e6"}

            //判断该操作是更改绑定，还是登陆
            Map<String, String> userName = (Map<String, String>) request.getSession().getAttribute("userName");
            System.out.println(userName);
            if(userName==null || userName.isEmpty() || userName.equals("null")) {
                System.out.println("登陆");
                check.join_message(MessageDTO, request, response);
            }
            else {
                System.out.println("绑定");
                //check.change_Bone(MessageDTO, request, response);
            }
            return;
        }

    }
}

